package com.yokead.controller.admin;

import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.yokead.common.OrderBaseControl;
import com.yokead.common.interceptor.LoginInterceptor;
import com.yokead.common.interceptor.NotLogin;
import com.yokead.service.UserService;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/5/16.
 */
@Controller
public class LoginControl extends OrderBaseControl {

    @Resource
    private UserService userService;

    @RequestMapping(value = "login.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String login() {
        return "admin/login";
    }

    @RequestMapping(value = "login_out.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String login_ing() {
        getSession().invalidate();
        return "redirect:/login.html";
    }

    /**
     * 登录验证
     *
     * @param name
     * @param pwd
     * @return
     */
    @RequestMapping(value = "login_ing.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String login_ing(String name, String pwd) {
        if (StringUtil.isEmpty(name, 4, 20))
            return JsonMessage.getString(300, "请输入正确的用户名");
        if (StringUtil.isEmpty(pwd, 6, 20))
            return JsonMessage.getString(300, "请输入正确的密码");
        boolean flag;
        try {
            flag = userService.login(name, pwd, true, getSession());
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("登录异常", e);
            return JsonMessage.getString(500, "登录系统异常");
        }
        if (flag) {
            setSessionAttribute(LoginInterceptor.SESSION_NAME, name);
            return JsonMessage.getString(200, "登录成功");
        }
        return JsonMessage.getString(400, "登录失败,请检查账号信息");
    }
}
